package com.sun.huazhi.aitaskservice.controller;

import com.sun.huazhi.aitaskservice.DTO.request.CreateVideoRequest;
import com.sun.huazhi.aitaskservice.DTO.response.VideoTaskResponse;
import com.sun.huazhi.aitaskservice.common.config.PythonApiProperties;
import com.sun.huazhi.aitaskservice.dao.entity.VideoTaskMessage;
import com.sun.huazhi.aitaskservice.service.impl.VideoTaskProducer;
import com.sun.huazhi.aitaskservice.service.impl.VideoTaskStoreService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.util.UUID;

@RestController
@RequestMapping("/api/video")
@Tag(name = "视频生成", description = "提供插花教学视频的生成和管理功能")
public class VideoController {

    @Autowired
    @Qualifier("pythonApiProperties")
    private PythonApiProperties apiProps;

    @Autowired
    private WebClient webClient;

    @Autowired
    private VideoTaskProducer videoTaskProducer;

    @Autowired
    private VideoTaskStoreService videoTaskStoreService;


    @PostMapping("/create")
    @Operation(summary = "创建教学视频", description = "异步生成视频")
    public Mono<ResponseEntity<VideoTaskResponse>> createVideo(@RequestBody CreateVideoRequest request) {
        if (request.getDuration() == null) {
            request.setDuration(60);
        }

        String taskId = UUID.randomUUID().toString();
        VideoTaskMessage message = new VideoTaskMessage(taskId, request.getTopic(), request.getStyle(), request.getDuration());
        videoTaskProducer.sendVideoTask(message);

        VideoTaskResponse pendingResponse = new VideoTaskResponse(taskId, "pending", null);
        videoTaskStoreService.savePending(taskId);
        return Mono.just(ResponseEntity.ok(pendingResponse));
    }


    @GetMapping("/task/{taskId}")
    @Operation(summary = "查询视频任务状态")
    public Mono<ResponseEntity<VideoTaskResponse>> getTaskStatus(@PathVariable String taskId) {
        return videoTaskStoreService.getTask(taskId)
                .map(ResponseEntity::ok)
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }

}
